import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:go_router/go_router.dart';
import '../providers/comic_provider.dart';
import '../models/comic.dart';
import 'mine/profile_screen.dart';
import '../utils/auth_utils.dart';

class ComicDetailScreen extends ConsumerWidget {
  final String comicId;

  const ComicDetailScreen({
    super.key,
    required this.comicId,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final comics = ref.watch(comicsProvider);
    final comic = comics.firstWhere(
      (c) => c.id == comicId,
      orElse: () => comics.first,
    );

    return Scaffold(
      backgroundColor: const Color(0xFF211839), // 主背景色
      body: CustomScrollView(
        slivers: [
          // App bar with cover image
          SliverAppBar(
            expandedHeight: 300,
            pinned: true,
            backgroundColor: const Color(0xFF211839), // AppBar背景色
            foregroundColor: Colors.white, // 白色图标
            flexibleSpace: FlexibleSpaceBar(
              background: Stack(
                fit: StackFit.expand,
                children: [
                  CachedNetworkImage(
                    imageUrl: comic.coverImageUrl,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(
                      color: const Color(0xFF2A1F3D), // 占位符背景色
                    ),
                    errorWidget: (context, url, error) => Container(
                      color: const Color(0xFF2A1F3D),
                      child: const Icon(
                        Icons.error,
                        color: Color(0xFF8B7AA8),
                      ),
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.transparent,
                          const Color(0xFF211839).withOpacity(0.8), // 渐变到主背景色
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

          // Comic info
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Title and basic info
                  Text(
                    comic.title,
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Colors.white, // 白色标题
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'By ${comic.author}',
                    style: const TextStyle(
                      fontSize: 16,
                      color: Color(0xFFB8B3C7), // 次要文字颜色
                    ),
                  ),
                  const SizedBox(height: 16),

                  // Rating and stats
                  Row(
                    children: [
                      const Icon(
                        Icons.star,
                        color: Color(0xFFFFA726), // 橙色星星
                        size: 20,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        comic.rating.toString(),
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        ),
                      ),
                      const SizedBox(width: 16),
                      Text(
                        '${comic.chaptersCount} chapters',
                        style: const TextStyle(
                          fontSize: 14,
                          color: Color(0xFFB8B3C7),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: _getStatusColor(comic.status),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          comic.status.toUpperCase(),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 16),

                  // Genres
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: comic.genres.map((genre) {
                      return Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 6,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFF6C5CE7).withOpacity(0.15), // 紫色背景
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(
                            color: const Color(0xFF6C5CE7).withOpacity(0.3),
                          ),
                        ),
                        child: Text(
                          genre,
                          style: const TextStyle(
                            color: Color(0xFF6C5CE7), // 紫色文字
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      );
                    }).toList(),
                  ),

                  const SizedBox(height: 20),

                  // Action buttons
                  Row(
                    children: [
                      Expanded(
                        flex: 2,
                        child: ElevatedButton.icon(
                          onPressed: () {
                            context.push('/reader/$comicId/1');
                          },
                          icon: const Icon(Icons.play_arrow),
                          label: const Text('Start Reading'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFF6C5CE7), // 紫色按钮
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            elevation: 4,
                            shadowColor: const Color(0xFF6C5CE7).withOpacity(0.3),
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: OutlinedButton.icon(
                          onPressed: () {
                            AuthUtils.requireLoginAction(context, ref, () {
                              // 处理收藏逻辑
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text('Added to bookmarks!'),
                                  backgroundColor: Color(0xFF00D4AA),
                                ),
                              );
                            });
                          },
                          icon: const Icon(Icons.bookmark_border),
                          label: const Text('Save'),
                          style: OutlinedButton.styleFrom(
                            foregroundColor: const Color(0xFF6C5CE7), // 紫色文字和边框
                            side: const BorderSide(color: Color(0xFF6C5CE7)),
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 24),

                  // Description
                  const Text(
                    'Description',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    comic.description,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Color(0xFFB8B3C7), // 次要文字颜色
                      height: 1.5,
                    ),
                  ),

                  const SizedBox(height: 24),

                  // Chapters section
                  const Text(
                    'Chapters',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                  const SizedBox(height: 12),
                ],
              ),
            ),
          ),

          // Chapters list
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                final chapterNumber = index + 1;
                return Container(
                  margin:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                  decoration: BoxDecoration(
                    color: const Color(0xFF2A1F3D), // 卡片背景色
                    border: Border.all(color: const Color(0xFF3D2F5A)), // 边框色
                    borderRadius: BorderRadius.circular(8),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: ListTile(
                    leading: CircleAvatar(
                      backgroundColor: const Color(0xFF6C5CE7).withOpacity(0.15),
                      child: Text(
                        chapterNumber.toString(),
                        style: const TextStyle(
                          color: Color(0xFF6C5CE7),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    title: Text(
                      'Chapter $chapterNumber',
                      style: const TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    subtitle: Text(
                      'Updated ${DateTime.now().subtract(Duration(days: index)).toString().split(' ')[0]}',
                      style: const TextStyle(
                        color: Color(0xFF8B7AA8), // 辅助文字颜色
                      ),
                    ),
                    trailing: const Icon(
                      Icons.chevron_right,
                      color: Color(0xFF8B7AA8),
                    ),
                    onTap: () {
                      context.push('/reader/$comicId/$chapterNumber');
                    },
                  ),
                );
              },
              childCount:
                  comic.chaptersCount.clamp(0, 10), // Show first 10 chapters
            ),
          ),

          const SliverToBoxAdapter(
            child: SizedBox(height: 24),
          ),
        ],
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'ongoing':
        return const Color(0xFF00D4AA); // 绿色
      case 'completed':
        return const Color(0xFF6C5CE7); // 紫色
      case 'hiatus':
        return const Color(0xFFFFA726); // 橙色
      default:
        return const Color(0xFF8B7AA8); // 灰色
    }
  }
}
